package com.zoke.daycarpool.ui;

import java.io.File;
import java.io.FileNotFoundException;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.zoke.daycarpool.R;
import com.zoke.daycarpool.base.BaseUi;
import com.zoke.daycarpool.config.CarpoolConfig;
import com.zoke.daycarpool.config.CarpoolConfig.HttpCode;
import com.zoke.daycarpool.config.CarpoolConfig.MessageCode;
import com.zoke.daycarpool.config.CarpoolConfig.PathStores;
import com.zoke.daycarpool.config.CarpoolParamStore;
import com.zoke.daycarpool.config.ImageConfig;
import com.zoke.daycarpool.config.UrlBank;
import com.zoke.daycarpool.domain.Token;
import com.zoke.daycarpool.domain.UserBeen;
import com.zoke.daycarpool.domain.UserInstense;
import com.zoke.daycarpool.fragment.MainFragment;
import com.zoke.daycarpool.fragment.MineFragment;
import com.zoke.daycarpool.util.LogTest;
import com.zoke.daycarpool.view.AppDialog;
import com.zoke.daycarpool.view.AppDialog.ChoseItemClick;
import com.zoke.support.http.HttpStores;
import com.zoke.support.http.ZokeParams;
import com.zoke.support.image.activity.GalleryActivity;
import com.zoke.support.image.activity.GalleryActivity.HandleType;
import com.zoke.support.image.activity.GalleryActivity.PhotoRequestCode;
import com.zoke.support.image.activity.ImageCutActivity;
import com.zoke.support.utils.FileUtil;
import com.zoke.support.utils.MessageHandlerList;
import com.zoke.support.view.ZokeToast;

/**
 * 个人编辑
 * 
 * @author JackWu
 * @version
 * @date 2015-1-2
 * @_QQ_ 651319154
 */
public class PersonEdit extends BaseUi {
	private TextView mSexTv;
	private AppDialog mSexDialog;
	private TextView mPosionTv;

	private UserBeen mUser;
	private ImageView mHeadIv;
	private TextView mUserNameTv;
	private TextView mPhoneTv;

	private String mTakePhotoPath = "";

	/** 编辑电话 **/
	public static final int EDITPHONECODE = 10;
	/** 编辑电话返回结果 **/
	public static final int RESULTCODE_PHONE = 11;
	/** 编辑名字返回结果 **/
	public static final int RESULTCODE_NAME = 12;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_edit);
		mTitleManager.setTitle("个人编辑").setLeftIcon(R.drawable.title_back);
		mEnableSwipeRight = true;
		findView();
		mUser = UserInstense.getInstense(getApplicationContext()).getUser();
		setData();
	}

	/** 设置数据 **/
	private void setData() {
		mSexTv.setText(mUser.getSex().equals("1") ? "男" : "女");
		mPosionTv.setText(mUser.getIdentify().equals("1") ? "乘客" : "车主");
		ImageLoader.getInstance().displayImage(mUser.getPhoto(), mHeadIv,
				ImageConfig.getHeadOptions());
		mUserNameTv.setText(mUser.getUserName());
		mPhoneTv.setText(mUser.getPhone());
	}

	/** 获取Sex 1或者2 **/
	private ZokeParams getSexParams(String sex) {
		ZokeParams mParams = getParams();
		mParams.put("sex", sex);
		return mParams;
	}

	/** 修改电话号码 **/
	private ZokeParams getMobileParams(String phone) {
		ZokeParams mParams = getParams();
		mParams.put("mobile", phone);
		return mParams;
	}

	/** 修改身份 **/
	private ZokeParams getIdentyParams(String identy) {
		ZokeParams mParams = getParams();
		mParams.put("identity", identy);
		return mParams;
	}

	/** 修改用户头像 **/
	private ZokeParams getUserPhotoParams(File photoFile) {
		ZokeParams mParams = getParams();
		try {
			mParams.put("photoFile", photoFile);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		return mParams;
	}

	/** 修改用户名 **/
	private ZokeParams getUserNameParams(String userName) {
		ZokeParams mParams = getParams();
		mParams.put("name", userName);
		return mParams;
	}

	private ZokeParams getParams() {
		ZokeParams mParams = CarpoolParamStore.getDefaultParam(mHashCode);
		mParams.setUrl(UrlBank.doEditPerson);
		mParams.put("sid", mUser.getUserId());
		mParams.put("token", Token.getTokener().getToken() + "");
		return mParams;
	}

	/** 修改用户信息 **/
	private void fetchEditUser(ZokeParams params) {
		HttpStores.getInstense(getApplicationContext()).find(params);
	}

	@Override
	protected void findView() {
		mSexTv = (TextView) findViewById(R.id.edit_item_tv_sex);
		mPosionTv = (TextView) findViewById(R.id.edit_positon_tv);
		mHeadIv = (ImageView) findViewById(R.id.edit_image_headphoto);
		mUserNameTv = (TextView) findViewById(R.id.edit_item_tv_username);
		mPhoneTv = (TextView) findViewById(R.id.edit_item_tv_phone);
	}

	/** 退出登陆 **/
	public void onClickExit(View view) {
		UserInstense.getInstense(getApplicationContext()).loginOut(mUser);
	}

	/** 性別点击 **/
	public void onClickSex(View view) {
		mSexDialog = new AppDialog(PersonEdit.this);
		mSexDialog.setDialogTitle("设置性别");
		mSexDialog.setchoseView(new ChoseItemClick() {
			@Override
			public void onItemClick(int position, View view) {
				mSexTv.setText(position == 0 ? "男" : "女");
				ZokeParams params = getSexParams(position == 0 ? "1" : "2");
				params.setOperator(HttpCode.EDIT_SEX);
				fetchEditUser(params);
			}
		});
		mSexDialog.setChoseFirstText("男");
		mSexDialog.setChoseSecText("女");
		mSexDialog.show();
	}

	@Override
	public void onSuccess(ZokeParams out) {
		super.onSuccess(out);
		String result = (String) out.getResult();
		try {
			JSONObject jo = new JSONObject(result);
			long token = jo.optLong("token");
			// 更新token
			if (token != 0)
				Token.getTokener().updateToken(token);
			LogTest.m("" + result);
		} catch (JSONException e) {
			e.printStackTrace();
		}

		switch (out.getOperator()) {
		case HttpCode.EDIT_HEAD:
			LogTest.tag("返回值=" + result);
			/**
			 * 03-26 17:52:54.227: I/wulijie(31911):
			 * {"code":"0","msg":"操作成功","result":{"photo":
			 * "\/static\/images\/20150326\/1427363575108.jpg"},"sid":"","token":"285
			 * 4 7 2 7 1 5 0 1 3 1 " }
			 */
			JSONObject jo;
			try {
				jo = new JSONObject(result);
				int code = jo.optInt("code");
				if (code == 0) {
					long token = jo.optLong("token");
					Token.getTokener().updateToken(token);
					JSONObject joo = jo.getJSONObject("result");
					String photo = CarpoolConfig.HTTPURL
							+ joo.optString("photo");
					mUser.setPhoto(photo);
					UserInstense.getInstense(getApplicationContext())
							.updateUser(mUser);
					ImageLoader.getInstance().displayImage(mUser.getPhoto(),
							mHeadIv, ImageConfig.getHeadOptions());

				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
			break;
		case HttpCode.EDIT_IDENTY:
			String identity = out.getStringValue("identity");
			mUser.setIdentify("" + identity);
			UserInstense.getInstense(getApplicationContext()).updateUser(mUser);
			MessageHandlerList.sendMessage(Main.class,
					MessageCode.UPDATE_MIENFRAGMENT);
			MessageHandlerList.sendMessage(MainFragment.class,
					MessageCode.UPDATE_MIENFRAGMENT);
			break;
		case HttpCode.EDIT_NAME:
			String name = out.getStringValue("name");
			mUser.setUserName(name);
			UserInstense.getInstense(getApplicationContext()).updateUser(mUser);
			break;
		case HttpCode.EDIT_PHONE:
			String phone = out.getStringValue("mobile");
			mUser.setPhone(phone);
			// 更新User数据
			UserInstense.getInstense(getApplicationContext()).updateUser(mUser);
			break;
		case HttpCode.EDIT_SEX:
			String sex = out.getStringValue("sex");
			mUser.setSex(sex);
			UserInstense.getInstense(getApplicationContext()).updateUser(mUser);
			break;

		default:
			break;
		}
		ZokeToast.show(getApplicationContext(), "修改成功");
		MessageHandlerList.sendMessage(MineFragment.class,
				MessageCode.UPDATE_MIENFRAGMENT);

	}

	@Override
	public void onFails(ZokeParams out) {
		super.onFails(out);
		ZokeToast.show(getApplicationContext(), "修改失败");
	}

	/** 身份 **/
	public void onClickSf(View view) {
		mSexDialog = new AppDialog(PersonEdit.this);
		mSexDialog.setDialogTitle("设置身份");
		mSexDialog.setchoseView(new ChoseItemClick() {
			@Override
			public void onItemClick(int position, View view) {
				mPosionTv.setText(position == 0 ? "我是乘客" : "我是车主");
				// -- 修改 身份
				ZokeParams params = getIdentyParams(position == 0 ? "1" : "2");
				params.setOperator(HttpCode.EDIT_IDENTY);
				fetchEditUser(params);
			}
		});
		mSexDialog.setChoseFirstText("我是乘客");
		mSexDialog.setChoseSecText("我是车主");
		mSexDialog.show();
	}

	/** 头像 **/
	public void onClickHead(View view) {
		mSexDialog = new AppDialog(PersonEdit.this);
		mSexDialog.setDialogTitle("设置头像");
		mSexDialog.setchoseView(new ChoseItemClick() {
			@Override
			public void onItemClick(int position, View view) {
				if (position == 0) {
					mTakePhotoPath = FileUtil.takePicture(PersonEdit.this,
							PathStores.getCachePath(PersonEdit.this));
					return;
				}
				if (position == 1) {
					mIntent.setClass(PersonEdit.this, GalleryActivity.class);
					mIntent.putExtra(GalleryActivity.HANDLETYPE,
							HandleType.CROP);
					startUIForResult(mIntent, PhotoRequestCode.CROP);
					return;
				}
			}
		});
		mSexDialog.setChoseFirstText("拍照");
		mSexDialog.setChoseSecText("相册");
		mSexDialog.show();
	}

	/** 点击修改名字 **/
	public void onClickName(View view) {
		mIntent = new Intent(PersonEdit.this, EditName.class);
		startUIForResult(mIntent, EDITPHONECODE);
	}


	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (data == null)
			return;

		if (requestCode == 1) {
			if (TextUtils.isEmpty(mTakePhotoPath)) {
				LogTest.tag("???");
				return;
			}
			LogTest.tag("ssss");
			// 拍照返回的图片过大 需要压缩到100kb
			Bitmap bit = FileUtil.compressBitmap(mTakePhotoPath, 100);
			String newFilePath = FileUtil.BitmapToFile(bit,
					PathStores.getCachePath(PersonEdit.this));
			mIntent = new Intent();
			mIntent.setClass(getApplicationContext(), ImageCutActivity.class);
			mIntent.putExtra(ImageCutActivity.CUTIMAGEPATH, newFilePath);
			startUIForResult(mIntent, PhotoRequestCode.CROP);
			return;
		}

		LogTest.tag("" + resultCode);
		if (resultCode == RESULTCODE_PHONE) {
			String phone = data.getStringExtra("phone");
			mPhoneTv.setText(phone);
			ZokeParams params = getMobileParams(phone);
			params.setOperator(HttpCode.EDIT_PHONE);
			fetchEditUser(params);
			return;
		}

		if (resultCode == RESULTCODE_NAME) {
			String name = data.getStringExtra("name");
			mUserNameTv.setText("" + name);
			ZokeParams params = getUserNameParams(name);
			params.setOperator(HttpCode.EDIT_NAME);
			fetchEditUser(params);
			return;
		}

		if (resultCode == PhotoRequestCode.CROP) {
			String path = data.getStringExtra(PhotoRequestCode.REQUESTKEY);
			LogTest.tag("path=" + path);
			File file = new File(path);
			if (!file.exists())
				return;
			ZokeParams params = getUserPhotoParams(file);
			params.setOperator(HttpCode.EDIT_HEAD);
			fetchEditUser(params);
			return;
		}

	}

	/** 点击修改电话 **/
	public void onClickPhone(View view) {
		mIntent = new Intent(PersonEdit.this, EditPhone.class);
		startUIForResult(mIntent, EDITPHONECODE);
	}
}
